package com.jhd.fuzhou.view.punishment;

import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.gson.Gson;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.view.login.FuzhouApplication;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.SpecialService;
import com.jhd.fuzhou.service.SupervisionService;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.EditTextView;
import com.jhd.fuzhou.util.StringShow;
import com.jhd.fuzhou.util.TimeUtil;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.vo.AdministrativePunishmentVo;
import com.jhd.fuzhou.vo.CheckValue;
import com.jhd.fuzhou.vo.GlobalDictionaryVo;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.OrganizationVo;
import com.jhd.fuzhou.vo.SupervisedUnitVo;
import com.jhd.fuzhou.vo.Supervisor;

import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class AdministrativeDetailActivity extends BaseActivity {

    private String data;
    private Context context=this;
    private AdministrativePunishmentVo administrativePunishmentVo;
    @BindView(R.id.btn_examine)Button btn_examine;//底部审核按钮
    @BindView(R.id.tv_unitName)TextView tv_unitName;//单位名称
    @BindView(R.id.tv_creditCode)TextView tv_creditCode;//企业信用代码
    @BindView(R.id.tv_registerAddress)TextView tv_registerAddress;//注册地址
    @BindView(R.id.tv_managementAddress)TextView tv_managementAddress;//经营地址
    @BindView(R.id.tv_company_number)TextView tv_company_number;//单位电话
    @BindView(R.id.tv_legalRepresentative)TextView tv_legalRepresentative;//法人代表
    @BindView(R.id.tv_gender)TextView tv_gender;//性别
    @BindView(R.id.tv_nation)TextView tv_nation;//民族
    @BindView(R.id.tv_duty)TextView tv_duty;//职务
    @BindView(R.id.tv_legalRepresentative_number)TextView tv_legalRepresentative_number;//法人联系电话
    @BindView(R.id.tv_contact_person)TextView tv_contact_person;//联系人
    @BindView(R.id.tv_contact_number)TextView tv_contact_number;//联系人电话
    @BindView(R.id.tv_accept_date)TextView tv_accept_date;//受理日期
    @BindView(R.id.tv_organization)TextView tv_organization;//受理机构
    @BindView(R.id.tv_accept_person)TextView tv_accept_person;//受理人
    @BindView(R.id.tv_case_source)TextView tv_case_source;//案件来源
    @BindView(R.id.tv_case_reason)TextView tv_case_reason;//案由
    @BindView(R.id.rb_status_1)RadioButton rb_status_1;//处罚程序,简单程序
    @BindView(R.id.rb_status_2)RadioButton rb_status_2;//处罚程序,一般程序
    @BindView(R.id.tv_case_explain)TextView tv_case_explain;//案情说明
    @BindView(R.id.tv_status)TextView tv_status;//状态
    @BindView(R.id.tv_step)TextView tv_step;//当前步骤
    @BindView(R.id.tv_step_name)TextView tv_step_name;//当前步骤名称
    @BindView(R.id.tv_step_next)TextView tv_step_next;//下一步状态
    @BindView(R.id.progressBar)ProgressBar progressBar;//
    @BindView(R.id.rel_date)RelativeLayout rel_date;//受理日期
    @BindView(R.id.rel_organization)RelativeLayout rel_organization;//受理机构
    @BindView(R.id.rel_accept_person)RelativeLayout rel_accept_person;//受理人
    @BindView(R.id.rel_case_source)RelativeLayout rel_case_source;//案件来源
    @BindView(R.id.rel_document)RelativeLayout rel_document;//文书附件
    @BindView(R.id.iv_process)ImageView iv_process;//状态栏的顶部颜色
    private SupervisedUnitVo supervisedUnitVo;
    private List<CheckValue> checkValueList;
    private List<Supervisor> supervisorList;
    private AlertDialog _alertDialog=null;
    private List<OrganizationVo> organizationVoList;
    private String stepNow;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_administrative_detail);
    }

    @Override
    protected void processLogic() {
        onBack();
        application.addPunishmentActivity(this);
        data=getIntent().getStringExtra("data");
        String isFinish = getIntent().getStringExtra("isFinish");
        if(isFinish.equals("1")){
            btn_examine.setVisibility(View.GONE);tv_status.setText("已完成");
            iv_process.setBackgroundResource(R.drawable.status_background_3);
        }else{
            tv_status.setText("未审核");
            iv_process.setBackgroundResource(R.drawable.status_background_1);
        }
        administrativePunishmentVo= JSON.parseObject(data, AdministrativePunishmentVo.class);
        getSupervisedUnitList(administrativePunishmentVo.getUnitName());
        getValue();//获取全局字典
        /*getOrgSelectorList();
        getPersonInfoList();*/
    }
    public void setData(){
        tv_unitName.setText(StringShow.showStr(administrativePunishmentVo.getUnitName()));//被监督单位
        tv_creditCode.setText(StringShow.showStr(supervisedUnitVo.getCreditCode()));//社会信用代码
        tv_registerAddress.setText(StringShow.showStr(supervisedUnitVo.getRegisterAddress()));
        tv_managementAddress.setText(StringShow.showStr(supervisedUnitVo.getManagementAddress()));
        tv_company_number.setText(StringShow.showStr(supervisedUnitVo.getContactNumber()));
        tv_legalRepresentative.setText(StringShow.showStr(supervisedUnitVo.getLegalRepresentative()));
        tv_gender.setText(StringShow.showStr(supervisedUnitVo.getGender()));
        tv_nation.setText(StringShow.showStr(supervisedUnitVo.getNation()));
        tv_duty.setText(StringShow.showStr(supervisedUnitVo.getPosition()));
        tv_legalRepresentative_number.setText(StringShow.showStr(""));
        tv_contact_person.setText(StringShow.showStr(supervisedUnitVo.getContactPerson()));
        tv_contact_number.setText(StringShow.showStr(supervisedUnitVo.getContactNumber()));
        tv_accept_date.setText(TimeUtil.getTime2(new Date()));
        tv_organization.setText(StringUtil.isNullOrEmpty(administrativePunishmentVo.getAcceptOrgan())?application.getOrgName():administrativePunishmentVo.getAcceptOrgan());
        tv_accept_person.setText(StringUtil.isNullOrEmpty(administrativePunishmentVo.getAcceptUser())?application.getName():administrativePunishmentVo.getAcceptUser());
        tv_case_explain.setText(StringUtil.isNullOrEmpty(administrativePunishmentVo.getContent())?"":administrativePunishmentVo.getContent());
        tv_case_reason.setText(StringShow.showStr(administrativePunishmentVo.getReason()));
        if("1".equals(administrativePunishmentVo.getProgressEsay())){
            rb_status_1.setChecked(true);
        }else if("2".equals(administrativePunishmentVo.getProgressEsay())){
            rb_status_2.setChecked(true);
        }
        /*administrativePunishmentVo.setAcceptTime(tv_accept_date.getText().toString());
        administrativePunishmentVo.setCompanyCode(tv_creditCode.getText().toString());
        administrativePunishmentVo.setAcceptOrgan(tv_organization.getText().toString());
        administrativePunishmentVo.setAcceptUser(tv_accept_person.getText().toString());
        administrativePunishmentVo.setReason(tv_case_reason.getText().toString());*/
    }
    public void setSource(List<CheckValue> checkValueList){
        for (CheckValue checkValue : checkValueList) {
            if(checkValue.getName().equals("案件来源")){
                List<GlobalDictionaryVo> globalDictionaryVos = checkValue.getGlobalDictionaryVoMap();

                for (GlobalDictionaryVo globalDictionaryVo : globalDictionaryVos) {
                    if(globalDictionaryVo.getKey().equals(administrativePunishmentVo.getSource())){
                        tv_case_source.setText(globalDictionaryVo.getValue());
                        break;
                    }
                }
            }
        }
    }

    @OnClick({R.id.rel_date,R.id.rel_organization,R.id.rel_accept_person,R.id.rel_case_source,R.id.btn_examine,R.id.rb_status_1,R.id.rb_status_2,R.id.rel_document,R.id.rel_law_basis})
    public void onClick(View v){
        switch (v.getId()){
            /*case R.id.rel_date:
                getTimeDialog3(tv_accept_date,context);
                administrativePunishmentVo.setAcceptTime(tv_accept_date.getText().toString());
                break;
            case R.id.rel_organization://受理机构
                if(organizationVoList!=null)dialogShow(tv_organization);
                break;
            case R.id.rel_accept_person://受理人
                if(supervisorList!=null)dialogShow(tv_accept_person);
                break;
            case R.id.rel_case_source://案件来源
                if(checkValueList!=null)dialogShow(tv_case_source);
                break;
            case R.id.rb_status_1://
                administrativePunishmentVo.setProgressEsay("1");
                break;
            case R.id.rb_status_2://
                administrativePunishmentVo.setProgressEsay("2");
                break;*/
            case R.id.rel_document:
                Intent intent_doc=new Intent(context,PunishmentDocumentActivity.class);
                intent_doc.putExtra("id",administrativePunishmentVo.getId());
                startActivity(intent_doc);
                break;
            case R.id.rel_law_basis:
                Intent intent_law_basis=new Intent(context,AdministrativeIllegalActivity.class);
                intent_law_basis.putExtra("id",administrativePunishmentVo.getId());
                startActivity(intent_law_basis);
                break;
            case R.id.btn_examine://审核
                Intent intent=new Intent(context, AuditAdministrativeActivity.class);
                Gson gson = new Gson();
                intent.putExtra("data", gson.toJson(administrativePunishmentVo));
                startActivityForResult(intent,1);
                break;
        }
    }

    public void getOrgSelectorList(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        SpecialService vs = retrofit.create(SpecialService.class);
        Call<JsonForResult> jsonForResultCall = vs.getOrgSelector(application.getAccessToken());//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){
                            organizationVoList = JSON.parseArray(jsonForResult.getData().toString(), OrganizationVo.class);

                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
//                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg;
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    public void getPersonInfoList(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.UC());//URL的头
        SupervisionService vs = retrofit.create(SupervisionService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("useSystem","1").addParam("status","1");
        Call<JsonForResult> jsonForResultCall = vs.getPersonInfoList(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()==null){
                            supervisorList=new ArrayList<Supervisor>();
                        }else{
                            supervisorList = JSON.parseArray(jsonForResult.getData().toString(), Supervisor.class);
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }
            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg;
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    public void dialogShow(TextView textView){
        LayoutInflater mLayoutInflater = LayoutInflater.from(this);
        View view = mLayoutInflater.inflate(R.layout.dialog_is_fit, null);
        final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context, R.style.ActionSheetDialogStyle);
        alertBuilder.setView(view);
        _alertDialog = alertBuilder.create();
        //获取当前Activity所在的窗体
        Window window = _alertDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        _alertDialog.show();
        ImageView iv_dismiss = (ImageView) view.findViewById(R.id.iv_dismiss);
        TextView title = (TextView) view.findViewById(R.id.title);
        title.setText("请选择");
        RecyclerView rv_question_answer = (RecyclerView) view.findViewById(R.id.rv_question_answer);
        LinearLayoutManager layoutManage = new LinearLayoutManager(context);
        rv_question_answer.setLayoutManager(layoutManage);
        SupervisorAdapter adapter=new SupervisorAdapter(textView,_alertDialog);
        rv_question_answer.setAdapter(adapter);
        WindowManager.LayoutParams params = window.getAttributes() ;
        params.width =(int) (getWindowManager().getDefaultDisplay().getWidth());                     //使用这种方式更改了dialog的框宽
        window.setAttributes(params);
    }

    public class SupervisorAdapter extends RecyclerView.Adapter<SupervisorAdapter.ViewHolder> {
        private TextView textView;
        private AlertDialog _alertDialog;
        private int checkPosition = -1;
        private List<GlobalDictionaryVo> globalDictionaryVos;

        public SupervisorAdapter(TextView textView, AlertDialog _alertDialog) {
            this._alertDialog = _alertDialog;
            this.textView = textView;
        }

        @NonNull
        @Override
        public SupervisorAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_choose, parent, false);
            SupervisorAdapter.ViewHolder viewHolder = new SupervisorAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull SupervisorAdapter.ViewHolder holder, int position) {
            if(textView==tv_organization){
                holder.tv_choose.setText(organizationVoList.get(position).getName());
            }else if(textView==tv_accept_person){
                holder.tv_choose.setText(supervisorList.get(position).getName());
            }else if(textView==tv_case_source){
                for (CheckValue checkValue : checkValueList) {
                    if (checkValue.getName().equals("案件来源")) {
                        globalDictionaryVos = checkValue.getGlobalDictionaryVoMap();
                        holder.tv_choose.setText(globalDictionaryVos.get(position).getValue());
                        break;
                    }
                }
            }
            if (textView==tv_organization) {
                if(textView.getText().toString().equals(organizationVoList.get(position).getName())){
                    holder.image.setVisibility(View.VISIBLE);
                }else{
                    holder.image.setVisibility(View.GONE);
                }
            }else if(textView==tv_accept_person){
                if(textView.getText().toString().equals(supervisorList.get(position).getName())){
                    holder.image.setVisibility(View.VISIBLE);
                }else{
                    holder.image.setVisibility(View.GONE);
                }
            }else if(textView==tv_case_source){
                if(textView.getText().toString().equals(globalDictionaryVos.get(position).getName())){
                    holder.image.setVisibility(View.VISIBLE);
                }else{
                    holder.image.setVisibility(View.GONE);
                }
            }
            holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(textView==tv_organization){
                        textView.setText(organizationVoList.get(position).getName());
                        administrativePunishmentVo.setAcceptOrgan(organizationVoList.get(position).getName());
                    }else if(textView==tv_accept_person){
                        textView.setText(supervisorList.get(position).getName());
                        administrativePunishmentVo.setAcceptUser(supervisorList.get(position).getName());
                    }else if(textView==tv_case_source){
                        for (CheckValue checkValue : checkValueList) {
                            if (checkValue.getName().equals("案件来源")) {
                                globalDictionaryVos = checkValue.getGlobalDictionaryVoMap();
                                textView.setText(globalDictionaryVos.get(position).getValue());
                                administrativePunishmentVo.setSource(globalDictionaryVos.get(position).getKey());
                                break;
                            }
                        }
                    }
                    EditTextView.TextViewChange(textView,context);
                    holder.image.setVisibility(View.VISIBLE);
                    _alertDialog.dismiss();
                    checkPosition = position;
                    notifyDataSetChanged();
                }
            });
            if (position == checkPosition) {
                holder.image.setVisibility(View.VISIBLE);
            } else {
                if (checkPosition != -1) {
                    holder.image.setVisibility(View.GONE);
                }
            }
        }

        @Override
        public int getItemCount() {
            if(textView==tv_organization){
                return organizationVoList.size();
            }else if(textView==tv_accept_person){
                return supervisorList.size();
            }else if(textView==tv_case_source){
                for (CheckValue checkValue : checkValueList) {
                    if (checkValue.getName().equals("案件来源")) {
                        globalDictionaryVos = checkValue.getGlobalDictionaryVoMap();
                        return globalDictionaryVos.size();
                    }
                }
            }
            return 0;
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_choose;
            ImageView image;
            RelativeLayout relativeLayout;

            public ViewHolder(View itemView) {
                super(itemView);
                this.tv_choose = itemView.findViewById(R.id.tv_choose);
                this.image = itemView.findViewById(R.id.image);
                this.relativeLayout = itemView.findViewById(R.id.relativeLayout);
            }
        }
    }


    public void getSupervisedUnitList(String unitName) {
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        SupervisionService vs = retrofit.create(SupervisionService.class);
        Map<String, Object> params =  new LinkedHashMap<String, Object>();
        params.put("unitName",unitName);
        if(!("1".equals(application.getOrgLevel()))){
            if(application.getOrgId()!=null)params.put("superviseOrgId",application.getOrgId());
        }
        Call<JsonForResult> jsonForResultCall = vs.getSupervisedUnitList(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){
                            List<SupervisedUnitVo> supervisedUnitVos = JSON.parseArray(jsonForResult.getData().toString(), SupervisedUnitVo.class);
                            supervisedUnitVo=supervisedUnitVos.get(0);
                            setData();
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
//                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg;
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    private void getValue(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.UC());//URL的头
        SupervisionService vs = retrofit.create(SupervisionService.class);
        JSONArray jsonArray=new JSONArray();
        jsonArray.add("案件进度");jsonArray.add("案件来源");/*jsonArray.add("送达方式");jsonArray.add("执行方式");jsonArray.add("执行结果");*/
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("nameList",jsonArray);
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"),
                JSON.toJSONString(params));
        Call<JsonForResult> jsonForResultCall = vs.getValueList(application.getAccessToken(), requestBody);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        //请求授权信息
                        if(jsonForResult.getData()!=null){
                            checkValueList= JSON.parseArray(jsonForResult.getData().toString(), CheckValue.class);
                            setSource(checkValueList);
                            for (CheckValue checkValue : checkValueList) {
                                if(checkValue.getName().equals("案件进度")){
                                    List<GlobalDictionaryVo> globalDictionaryVos = checkValue.getGlobalDictionaryVoMap();

                                    for (GlobalDictionaryVo globalDictionaryVo : globalDictionaryVos) {
                                        if(globalDictionaryVo.getValue().equals(administrativePunishmentVo.getProgress())){
                                            if(Integer.valueOf(globalDictionaryVo.getKey())==globalDictionaryVos.size()){
                                                progressBar.setProgress(100);
                                            }else{
                                                progressBar.setProgress((Integer.valueOf(globalDictionaryVo.getKey())*100)/9);
                                            }
                                            if(globalDictionaryVo.getKey().equals("1")){
                                                btn_examine.setText("提交");
                                            }else if(globalDictionaryVo.getKey().equals("9")){
                                                btn_examine.setVisibility(View.GONE);
                                            }
                                            stepNow=globalDictionaryVo.getKey();
                                            tv_step.setText(globalDictionaryVo.getKey()+"/"+9);
                                            tv_step_name.setText(globalDictionaryVo.getValue());
                                            if(Integer.valueOf(globalDictionaryVo.getKey())<9){
                                                tv_step_next.setText(""+(Integer.valueOf(globalDictionaryVo.getKey())+1)+"/9"+globalDictionaryVos.get(Integer.valueOf(globalDictionaryVo.getKey())).getValue());
                                            }
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    UtilHelper.alertMsg(context, "错误", e.getMessage());
                }
            }
            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "获取检测项目失败!";
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode ==RESULT_OK) {
            if(data.getStringExtra("position").equals("1")){
                finish();
            }
        }
    }

}